import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';
import axios from '@/plugins/axios';
import { ref } from 'vue';

export interface Package {
  id: number;
  fileName: string;
  filePath: string;
  fileSize: number;
  version: string;
  suffix: string;
  iconUrl: string;
  officialUrl: string;
}

export const usePackageStore = defineStore('package', () => {
  const packages = ref<Package[]>([]);
  const total = ref(0);

  const fetchPackages = async (page: number, size: number) => {
    try {
      const response = await axios.get(`/api/package?page=${page}&size=${size}`);
      packages.value = response.data.data.content || [];
      total.value = response.data.data.totalElements || 0;
      return packages.value;
    } catch (error: any) {
      ElMessage.error('获取安装包列表失败: ' + error.message);
      throw error;
    }
  };

  const searchPackages = async (query: string) => {
    try {
      ElMessage.info('正在搜索安装包...');
      const response = await axios.get(`/api/package/search?q=${encodeURIComponent(query)}`);
      packages.value = response.data.data.content || [];
      total.value = response.data.data.totalElements || 0;
      return packages.value;
    } catch (error: any) {
      ElMessage.error('搜索安装包失败: ' + error.message);
      throw error;
    }
  };

  const uploadPackage = async (formData: FormData) => {
    try {
      const response = await axios.post('/api/package/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      return response.data.data; // 返回 Package 数据
    } catch (error: any) {
      ElMessage.error('上传安装包失败: ' + error.message);
      throw error;
    }
  };

  const updatePackage = async (pkg: Package) => {
    try {
      await axios.put('/api/package', pkg);
      ElMessage.success('更新成功');
    } catch (error: any) {
      ElMessage.error('更新失败: ' + error.message);
      throw error;
    }
  };

  const deletePackage = async (id: number) => {
    try {
      await axios.delete(`/api/package/${id}`);
      ElMessage.success('删除成功');
      await fetchPackages(0, 20); // 删除后刷新第一页
    } catch (error: any) {
      ElMessage.error('删除失败: ' + error.message);
      throw error;
    }
  };

  return { packages, total, fetchPackages, searchPackages, uploadPackage, updatePackage, deletePackage };
});